﻿using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Wicture.DbRESTFul;
using Wicture.DbRESTFul.Cache;
using Wicture.QPZS.EPC.API.Domain;
using Wicture.QPZS.EPC.API.Domain.Entities;

namespace Wicture.QPZS.EPC.API.Throttlings
{
    public class PackageFrequencyThrotting : FrequencyThrotting
    {
        public override decimal Order => 6;

        protected override bool NeedFrequency(ThrottlingContext context)
        {
            var frequency = context.AccountPackage?.Frequency;
            return frequency > 0;
        }

        protected override void SetFrequency(ThrottlingContext context, InvocationFrequency invocationFrequency)
        {
            var frequency = context.AccountPackage?.Frequency;
            if (invocationFrequency.Total > frequency)
            {
                LoggerManager.Logger.LogWarning($"{context.AccountName}: 调用频率超出: {invocationFrequency.Total} / {frequency}.");
                throw new LogicalException($"接口调用太频繁，超出每分钟{frequency}次。", 603);
            }
            invocationFrequency.Total += 1;
        }
    }
}
